﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// 客户端缓存
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class ModifiedAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 缓存时间
        /// </summary>
        private int _expires;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Expires"></param>
        public ModifiedAttribute(int Expires = 60)
        {
            this._expires = Expires;
        }


        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Result == null || actionExecutedContext.HttpContext.Response.StatusCode >= 300)
            {
                base.OnActionExecuted(actionExecutedContext);
                return;
            }

      
            actionExecutedContext.HttpContext.Response.Headers.Add("Last-Modified", new StringValues(DateTimeOffset.Now.AddMinutes(_expires).ToString(CultureInfo.InvariantCulture)));
            base.OnActionExecuted(actionExecutedContext);
        }

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var header = actionContext.HttpContext.Request.Headers;
            if (header.TryGetValue("If-Modified-Since", out StringValues value))
            {
                DateTimeOffset expiredTime = DateTimeOffset.Parse(value.ToString());
                if (expiredTime > DateTimeOffset.Now)
                {
                    actionContext.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.NotModified);
                    return;
                }
            }
            base.OnActionExecuting(actionContext);
        }


    }
}